﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Windows.Interop;
using System.Collections;
using DoubleH.Utility.Configuration;
using System.Collections.ObjectModel;

namespace POS.StoreTemplete
{
    /// <summary>
    /// StoreSales.xaml 的交互逻辑
    /// </summary>
    public partial class PageSale : Page, ISaleTemplete
    {
        public PageSale()
        {
            InitializeComponent();

            InitVar();
            InitEvent();
        }

        private void InitVar()
        {
            this.Background = App.BackgroundBrush;
            this.Foreground = App.ForegroundBrush;
            foreach (UIElement ui in mainGrid.Children)
            {
                Control c = ui as Control;
                if (c != null)
                {
                    c.Background = App.BackgroundBrush;
                    c.Foreground = App.ForegroundBrush;
                }
            }

            if (!DoubleHConfig.AppConfig.ShowCashboxMoney)
            {
                labelCashboxMoney.Visibility = Visibility.Hidden;
                labelCashboxMoneyTitle.Visibility = Visibility.Hidden;
            }

            dataGridObject.ShowBodyContexMenu = false;
            dataGridObject.ShowAverage = false;
            dataGridObject.EnableText = string.Empty;
            dataGridObject.CanUserAddRows = false;
            dataGridObject.CanSelectProduct = false;
            dataGridObject.SelectionUnit = DataGridSelectionUnit.FullRow;
            dataGridObject.IsSale = ProductS.GetProductS.EnumProductS.可销售商品;

            textBoxInput.Focus();
        }

        private void InitEvent()
        {
            textBoxInput.KeyDown += (ss, ee) => { if (ee.Key == Key.Enter)PressEnter(); };
            textBoxInput.PreviewKeyDown += (ss, ee) => { TextBoxKeyPreviewDown(ee.Key); };
        }

        private void TextBoxKeyPreviewDown(Key key)
        {
            switch (key)
            {
                case Key.Delete:
                    dataGridObject.RemoveSelectedItem();
                    break;

                case Key.Down:
                    if (dataGridObject.SelectedIndex + 1 < dataGridObject.Count)
                        dataGridObject.SelectedIndex += 1;
                    break;

                case Key.Up:
                    if (dataGridObject.SelectedIndex > 0)
                        dataGridObject.SelectedIndex -= 1;
                    break;
            }
        }

        private void PressEnter()
        {
            if (string.IsNullOrEmpty(textBoxInput.Text))
            {
                if (!dataGridObject.HasItems)
                    return;

                App.MWindow.ChangeUI(MainWindow.EnumUI.结账);

                if (App.SaleMode)
                    if (App.Order.Id != -1)
                    {
                        Table.ErrorS.WriteLogFile(App.Order.OrderNO + " 成功交易");
                        NewOrder();
                    }

                return;
            }

            if (textBoxInput.Text.StartsWith("++"))
            {
                ChangedQuantity();
                textBoxInput.Clear();
                return;
            }
            if (textBoxInput.Text.StartsWith("--"))
            {
                ChangedPrice();
                textBoxInput.Clear();
                return;
            }
            if (textBoxInput.Text.StartsWith(".."))
            {
                ChangeVipNO();
                textBoxInput.Clear();
                return;
            }
            if (textBoxInput.Text.StartsWith("//"))
                if (GetGuaDan())
                {
                    textBoxInput.Clear();
                    return;
                }

            Table.ProductS product = null;
            ObservableCollection<Table.ProductS> ps = Table.ProductS.GetListForPos(textBoxInput.Text.Trim());
            if (ps == null)
                return;

            if (ps.Count == 1)
                product = ps[0];
            else if (ps.Count > 1)
            {
                SelectProduct sp = new SelectProduct();
                sp.Owner = App.MWindow;
                sp.ItemsSource = ps;
                sp.ShowDialog();
                product = sp.Product;
            }

            if (product == null)
                MessageWindow.Show("商品不存在");
            else
            {
                product.InitPrice(null);
                dataGridObject.InsertItem(0, product);
                dataGridObject.SelectedIndex = 0;
            }
            if (dataGridObject.Count > 0)
                dataGridObject.SelectedIndex = 0;

            textBoxInput.Clear();
            textBoxInput.Focus();
        }

        private void ChangedQuantity()
        {
            if (dataGridObject.SelectedItem == null)
                return;
            
            double d = 0; string str = string.Empty;
            if (!textBoxInput.Text.StartsWith("++"))
                return;

            if (!double.TryParse(textBoxInput.Text.Remove(0, 2), out d))
                return;

            dataGridObject.CalcQuantity(dataGridObject.SelectedItem,Math.Abs(d), true);
        }

        private void ChangedPrice()
        {
            if (dataGridObject.SelectedItem == null)
                return;

            if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.更改零售价) > Table.UserS.EnumAuthority.编辑)
            {
                MessageWindow.Show("权限不足");
                return;
            }

            double d = 0; string str = string.Empty;
            if (!textBoxInput.Text.StartsWith("--"))
                return;

            if (!double.TryParse(textBoxInput.Text.Remove(0, 2), out d))
                return;

            ((Table.ProductS)dataGridObject.SelectedItem)._TempPrice = Math.Abs(d);
        }

        private void ChangeVipNO()
        {
            if (!textBoxInput.Text.StartsWith(".."))
                return;
            if (textBoxInput.Text == "..")
            {
                dataGridObject.CorS = null;
                labelRemainIntegral.Content = null;
                labelVipNO.Content = null;
                return;
            }

            Table.CorS vip = Table.CorS.GetVipObject(textBoxInput.Text.Remove(0, 2));
            textBoxInput.Clear();
            if (vip == null || vip.Id == -1)
            {
                MessageWindow.Show("会员不存在");
                return;
            }
            if (vip.VipDateEnd < DateTime.Now)
            {
                MessageWindow.Show("会员已过期");
                return;
            }

            ClassGuaDan gd = App.GuaDan.FirstOrDefault<ClassGuaDan>(c => c.CorSId == vip.Id);
            if (gd != null)
                ConfigGuaDan(gd);
            else
            {
                labelVipNO.Content = vip.VipNO;
                labelRemainIntegral.Content = vip.VipRemainIntegral;
                App.Order.CorSId = vip.Id;
                dataGridObject.CorS = vip;
            }
        }

        private bool GetGuaDan()
        {
            string str = textBoxInput.Text.Remove(0, 2).Trim();
            if (string.IsNullOrEmpty(str))
                return false;

            int it = -1;
            if (int.TryParse(str, out it))
            {
                if (it < 1)
                    return false;

                if (it > App.GuaDan.Count)
                    return false;
                
                ConfigGuaDan(App.GuaDan[it-1]);
                return true;
            }
            else
                return false;
        }

        private void ConfigGuaDan(ClassGuaDan gd)
        {
            App.Order = gd.ToOrder();
            dataGridObject.ItemsSource = App.Order.ProductSList;
            labelVipNO.Content = gd.VipNO;
            labelRemainIntegral.Content = gd.RemainIntegral;
            App.GuaDan.Remove(gd);
            GuaDan();
        }

        //接口
        public void Init()
        {
            dataGridObject.InitColumns(DataTableText.Pos客户端);
            labelCashboxMoney.Content = DoubleHConfig.AppConfig.PosCashboxMoney;
        }

        public Int64 CorSId { get { return App.Order.CorSId; } }

        public string VipNO { get { return labelVipNO.Content.ToString(); } }

        public string RemainIntegral { get { return labelRemainIntegral.Content.ToString(); } }

        public void NewOrder()
        {
            if (App.Order != null)
            {
                labelPreOrderNO.Content = App.Order.OrderNO;
                labelPreMoney.Content = App.Order.Money;
                labelVipNO.Content = "无";
                labelRemainIntegral.Content = string.Empty;
                labelCashboxMoney.Content = DoubleHConfig.AppConfig.PosCashboxMoney;
            }
            App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单) ;
            dataGridObject.ItemsSource = App.Order.ProductSList;
            dataGridObject.CorS = null;
        }

        public void GuaDan()
        {
            labelGuaDan.Content = App.GuaDan.Count;
        }
    }
}